package imageServer.web;

import imageServer.config.ImageConfigVo;
import imageServer.utils.ImageUtils;
import imageServer.vo.ImageUploadResponseVo;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by xiaoqian on 2016/9/7.
 */
abstract public class AbstractUploadAct {
    private static final Logger logger = LoggerFactory.getLogger(AbstractUploadAct.class);
    @Autowired
    protected ImageConfigVo imageConfigVo;

    public ImageConfigVo getImageConfigVo() {
        return imageConfigVo;
    }

    public void setImageConfigVo(ImageConfigVo imageConfigVo) {
        this.imageConfigVo = imageConfigVo;
    }

    protected List<ImageUploadResponseVo> uploadFiles(HttpServletRequest request,  MultipartHttpServletRequest mrequest) throws IOException {
        List<ImageUploadResponseVo> responseVos = new ArrayList<ImageUploadResponseVo>();
        String saveFilePathStr = getImageConfigVo().getFullSaveFilePath()+new DateTime().toString("yyyy-MM-dd")+"/";
        File savefilePathDir = new File(saveFilePathStr);
        if(!savefilePathDir.exists()){
            savefilePathDir.mkdirs();
        }
        for (MultipartFile file : mrequest.getFileMap().values()) {
            if(file!=null && !file.isEmpty()){
                ImageUploadResponseVo responseVo = new ImageUploadResponseVo();
                //强制名称
                String fileName = null;
                String fileNameExt = ImageUtils.getFileNameExt(file.getOriginalFilename());
                if(mrequest.getParameter(file.getName() + "_name")!=null){
                    fileName = request.getParameter(file.getName() + "_name").toString();
                    if(fileName.indexOf(".")<0){
                        fileName=fileName+"."+fileNameExt;
                    }
                }else if (request.getParameter(file.getName() + "_sourceName")!=null || !ImageUtils.isImage(fileNameExt)){
                    fileName = file.getOriginalFilename();
                }else{
                    if(file.getSize()<(1024)){
                        fileName = DigestUtils.md5DigestAsHex(file.getBytes())+"."+fileNameExt;
                    }else{
                        fileName = DigestUtils.md5DigestAsHex(file.getOriginalFilename().getBytes())+"."+fileNameExt;
                    }
                }
                File newFile = new File(saveFilePathStr+fileName);

                if(newFile.exists()){
                    newFile = new File(saveFilePathStr+System.currentTimeMillis()+fileName);
                }
                file.transferTo(newFile);
                String newFilePath = newFile.getAbsolutePath().replaceAll("//","/").replaceAll("\\\\", "/");
                responseVo.setFilePath(newFilePath.substring(newFilePath.indexOf(getImageConfigVo().getPath())));
                responseVo.setAbsoluteFilePath(getImageConfigVo().getDomain()+ responseVo.getFilePath());
                responseVo.setName(file.getName());

                if("true".equals(request.getParameter(file.getName()+"_mark")) && ImageUtils.isImage(fileNameExt)){
                    String fileStr = newFile.getAbsolutePath()+"_mark."+fileNameExt;
                    File waterMarkFile = new File(fileStr);
                    //水印处理
                    Thumbnails
                            .of(newFile)
                            .watermark(Positions.BOTTOM_RIGHT , getImageConfigVo().getBufferedImage(),getImageConfigVo().getWqterQuality())
                            .scale(1d)
                            .toFile(waterMarkFile);
                    fileStr = fileStr.replaceAll("//", "/").replaceAll("\\\\", "/");
                    responseVo.setMarkFilePath(fileStr.substring(fileStr.indexOf(getImageConfigVo().getPath())));
                    responseVo.setMarkAbsoluteFilePath(getImageConfigVo().getDomain() + responseVo.getMarkFilePath());
                }
                //如果是图片
                if(ImageUtils.isImage(fileNameExt)){
                    BufferedImage bufferedImage = ImageIO.read(newFile);
                    responseVo.setWidth(bufferedImage.getWidth());
                    responseVo.setHeight(bufferedImage.getHeight());
                }

                //判断是否
                responseVos.add(responseVo);
            }
        }
        return  responseVos;
    }
}
